import i18n from '@/i18n'
import { AppLogger, Assist, createInstance, getNodeEnv } from '@libs/lhy-common'
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { CoreConfigFactory } from './core-config-factory'
import { CoreConfig } from './entity/core-config.entity'

@Injectable()
export class CoreConfigService<T extends CoreConfig = CoreConfig> {
  /**
   * 实际配置文件数据
   */
  private data: T

  /**
   * getter
   */
  get config() {
    Assist.threw(!this.data, i18n.t('lhy-core.core-config.core-config.121487-0'))
    return this.data
  }

  constructor(
    private readonly configService: ConfigService,
    readonly target: Function
  ) {
    const newData = createInstance(target)

    // 支持原型链继承方式取值
    while (target) {
      CoreConfigFactory.getConfigProperties(target).forEach(propertyKey => {
        if (!newData[propertyKey]) {
          newData[propertyKey] = this.configService.get(propertyKey)
        }
      })
      target = Object.getPrototypeOf(target)
    }
    this.data = newData as T

    AppLogger.info(CoreConfigService.name, () =>
      i18n.t('lhy-core.core-config.core-config.121487-1', { args: [getNodeEnv(), JSON.stringify(this.data, null, 2)] })
    )
  }
}
